package com.longer.playhelper.view.fragment;


import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.app.Fragment;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.utils.TimeUtils;
import com.bumptech.glide.Glide;
import com.jude.rollviewpager.RollPagerView;
import com.jude.rollviewpager.adapter.StaticPagerAdapter;
import com.jude.rollviewpager.hintview.ColorPointHintView;
import com.longer.playhelper.Application;
import com.longer.playhelper.R;
import com.longer.playhelper.adapter.MenuLoveAdapter;
import com.longer.playhelper.modle.bean.Lost;
import com.longer.playhelper.modle.bean.Love;
import com.longer.playhelper.presenter.Fragement_MainPresenter;
import com.longer.playhelper.utlis.Toast;
import com.longer.playhelper.view.activity.Add_lostActivity;
import com.longer.playhelper.view.activity.BaiduMapActivity;
import com.longer.playhelper.view.activity.ImageActivity;
import com.longer.playhelper.view.activity.Lost_Activity;
import com.longer.playhelper.view.activity.MainActivity;
import com.longer.playhelper.view.iview.IFragmentMainView;
import com.tapadoo.alerter.Alerter;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;

public class MainFragment extends Fragment implements IFragmentMainView {


    @Bind(R.id.card_menu_love)
    CardView cardMenuLove;
    @Bind(R.id.recycle_item_menu_love)
    RecyclerView recycleItemMenuLove;
    RollPagerView mRollViewPager;
    @Bind(R.id.menu_help)
    LinearLayout menuHelp;
    @Bind(R.id.menu_love)
    LinearLayout menuLove;
    @Bind(R.id.menu_lost)
    LinearLayout menuLost;
    @Bind(R.id.menu_news)
    LinearLayout menuNews;
    private View view;
    Context context;
    private Fragement_MainPresenter menuPresenter = new Fragement_MainPresenter(this);


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_main, container, false);
        context = getActivity();
        setpic();
        ButterKnife.bind(this, view);
        init();
        return view;
    }

    private void init() {
        //设置中间菜单的点击事件
        menuHelp.setOnClickListener(onClick_help);
        menuLost.setOnClickListener(onClick_lost);
        menuLove.setOnClickListener(onClick_love);
        menuNews.setOnClickListener(onClick_news);

        setmenu_lost();//设置失物招领卡片
        menuPresenter.setMenuLove();//设置表白墙卡片
        setmenu_message();//设置每日推荐
        setmenu_pic();//设置每日一图
    }

    View.OnClickListener onClick_help = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //检查权限，如果没有权限不让进
            checkPermission();
        }
    };

    private void checkPermission() {
        if (AndPermission.hasPermission(context, Manifest.permission.READ_PHONE_STATE)
                && AndPermission.hasPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION)
                && AndPermission.hasPermission(context, Manifest.permission.ACCESS_FINE_LOCATION)) {
            // 有权限，直接do anything.
            startActivity(new Intent(context, BaiduMapActivity.class));
        } else {
            // 申请权限。
            AndPermission.with(getActivity())
                    .requestCode(100)
                    .permission(Manifest.permission.READ_PHONE_STATE, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION)
                    .send();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        // 只需要调用这一句，其它的交给AndPermission吧，最后一个参数是PermissionListener。
        AndPermission.onRequestPermissionsResult(requestCode, permissions, grantResults, listener);
    }

    private PermissionListener listener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, List<String> grantedPermissions) {
            // 权限申请成功回调。
            if (requestCode == 100) {
                Log.d("tip", "100");
                startActivity(new Intent(context, BaiduMapActivity.class));
            } else if (requestCode == 101) {
                Log.d("tip", "101");
            }
        }

        @Override
        public void onFailed(int requestCode, List<String> deniedPermissions) {
            // 权限申请失败回调。
            Alerter.create(getActivity())
                    .setTitle("没有权限将无法使用！")
                    .setBackgroundColorRes(R.color.colorAccent)
                    .show();
        }
    };
    View.OnClickListener onClick_love = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            MainActivity.setBottomNavigation(1);
        }
    };
    View.OnClickListener onClick_news = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Alerter.create(getActivity())
                    .setTitle("程序员正在加班中...")
                    .setBackgroundColorRes(R.color.colorAccent)
                    .show();
        }
    };
    View.OnClickListener onClick_lost = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            MainActivity.setBottomNavigation(2);
        }
    };


    /**
     * 设置图片轮显
     */
    public void setpic() {
        mRollViewPager = (RollPagerView) view.findViewById(R.id.roll_view_pager);
        mRollViewPager.setAnimationDurtion(700);
        mRollViewPager.setAdapter(new TestNormalAdapter());
        mRollViewPager.setHintView(new ColorPointHintView(context, Color.parseColor("#f0FF4081"), Color.parseColor("#a0ffffff")));
    }


    private class TestNormalAdapter extends StaticPagerAdapter {
        private int[] imgs = {
                R.mipmap.home_1,
                R.mipmap.home_2,
                R.mipmap.home_3,
                R.mipmap.home_4
        };

        @Override
        public View getView(ViewGroup container, final int position) {
            ImageView view = new ImageView(container.getContext());
            view.setImageResource(imgs[position]);
            view.setScaleType(ImageView.ScaleType.CENTER_CROP);
            view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            return view;
        }

        @Override
        public int getCount() {
            return imgs.length;
        }
    }

    /**
     * 设置每日推荐
     */
    public void setmenu_message() {
        view.findViewById(R.id.card_menu_message).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Alerter.create(getActivity())
                        .setTitle("程序员正在加班中...")
                        .setBackgroundColorRes(R.color.colorAccent)
                        .show();
            }
        });
    }

    /**
     * 设置每日一图
     */
    public void setmenu_pic() {
        view.findViewById(R.id.card_menu_pic).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, ImageActivity.class);
                intent.putExtra("pic_id", R.mipmap.home_3);
                intent.putExtra("title_name", "每日一图");
                startActivity(intent);
            }
        });
    }

    /**
     * 设置表白墙卡片
     */
    @Override
    public void setmenu_love(List<Love> list) {
//        view.findViewById(R.id.ll_item_menu_love).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {//底部更多表白按钮
////                startActivity(new Intent(context, LoveActivity.class));
//            }
//        });
        recycleItemMenuLove.setHasFixedSize(true);

        LinearLayoutManager layoutManager = new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false);
        recycleItemMenuLove.setLayoutManager(layoutManager);

        MenuLoveAdapter mAdapter = new MenuLoveAdapter(list, context);
        recycleItemMenuLove.setAdapter(mAdapter);
    }

    @Override
    public void setmenu_love_cardshow() {
        cardMenuLove.setVisibility(View.VISIBLE);
    }

    @Override
    public void setmenu_love_cardhide() {
        cardMenuLove.setVisibility(View.GONE);
    }


    /**
     * 设置失物招领卡片
     */
    private void setmenu_lost() {
        view.findViewById(R.id.tv_menu_lostadd).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {//底部我要发布按钮
                if (Application.my != null) {
                    startActivity(new Intent(context, Add_lostActivity.class));
                    Log.d("tip","have");
                } else {
                    Log.d("tip","null");
                    Alerter.create(getActivity())
                            .setTitle("登录之后才能发布哦！")
                            .show();
                }
            }
        });
        //得到数据
        BmobQuery<Lost> query = new BmobQuery<Lost>();
        query.order("-createdAt");
        query.setLimit(1);
        query.findObjects(new FindListener<Lost>() {
                              @Override
                              public void done(List<Lost> list, BmobException e) {
                                  if (e != null) {
                                      Log.d("查询失物招领出错", e.toString());
                                      e.printStackTrace();
                                      Toast.show("查询出错(" + e.getErrorCode() + ")");
                                      return;
                                  }
                                  Lost good = list.get(0);
                                  ImageView iv = (ImageView) view.findViewById(R.id.iv_menu_lost);
                                  if (good.getPic1() != null) {
                                      Glide.with(context).load(good.getPic1().getUrl())
                                              .placeholder(R.mipmap.imageselector_photo)
                                              .error(R.mipmap.imageselector_photo)
                                              .into(iv);
                                  } else {
                                      Glide.with(context).load(R.drawable.lost_nopic)
                                              .into(iv);
                                  }
                                  TextView tv = (TextView) view.findViewById(R.id.tv_menu_lost_name);
                                  tv.setText(good.getTitle());
                                  tv = (TextView) view.findViewById(R.id.tv_menu_lost_info);
                                  tv.setText(good.getInfor());
                                  tv = (TextView) view.findViewById(R.id.tv_menu_lost_time);
                                  tv.setText(TimeUtils.getFriendlyTimeSpanByNow(good.getCreatedAt()));

                                  //设置失物的点击事件
                                  final Lost good1 = good;
                                  view.findViewById(R.id.ll_menu_lost).setOnClickListener(new View.OnClickListener() {
                                      @Override
                                      public void onClick(View v) {
                                          Intent intent = new Intent(context, Lost_Activity.class);
                                          ActivityOptionsCompat options =
                                                  ActivityOptionsCompat.makeSceneTransitionAnimation(getActivity(),
                                                          v.findViewById(R.id.iv_menu_lost), getString(R.string.transition_goods_img));
                                          intent.putExtra("Lost", good1);
                                          ActivityCompat.startActivity(getActivity(), intent, options.toBundle());
                                      }
                                  });
                              }
                          }
        );
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
}
